import { defineComponent } from 'vue';
import {
  complaintList,
  complaintDetail,
  getComplaint,
  dReportDetail
} from '@/api/home';
import SheltV2 from '../../common/SheltV2';
import Echarts from '@/components/Echarts';
import {
  ElIcon,
  ElImage,
  ElTooltip,
  ElDatePicker,
  ElDialog,
  ElTable,
  ElTableColumn,
  ElLoading
} from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import './index.less';

export default defineComponent({
  name: 'Complaint',
  setup() {
    const { VITE_STATIC_URL } = import.meta.env;
    const loadingCommon = ref(false);
    const loadingDetail = ref(false);
    const loadingReport = ref(false);
    const reportVisible = ref(false);
    const dialogVisible = ref(false);
    const dialogDetailVisible = ref(false);
    const reportData = ref([]);
    const tableData = ref([]);
    const detailData = ref({}) as AnyObject;
    const date = reactive({
      chart: new Date(),
      list: new Date(),
      detail: new Date(),
      report: new Date()
    }) as AnyObject;
    const pageable = reactive({
      page: 1,
      pageSize: 15,
      total: 0
    });
    const detail = ref({}) as AnyObject;
    const option = ref({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      color: ['#4a74ea', '#eb833c', '#ffc61c'],
      legend: {
        data: ['目标客诉', '实际客诉', '降幅率'],
        icon: 'circle',
        itemGap: 30,
        itemWidth: 10
      },
      grid: {
        left: 50
        // right: '100%',
        // top: "10%",
        // bottom: '90%'
      },
      xAxis: [
        {
          type: 'category',
          data: [],
          axisPointer: {
            type: 'shadow'
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false
          }
        }
      ],

      yAxis: [
        {
          type: 'value'
        },
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '目标客诉',
          type: 'bar',

          barWidth: 15,
          data: []
        },
        {
          name: '实际客诉',
          type: 'bar',

          barWidth: 15,
          data: []
        },
        {
          name: '降幅率',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          lineStyle: {
            width: 3
          },
          symbol: 'none',
          tooltip: {
            valueFormatter: function (value: string) {
              return value + '%';
            }
          },
          data: []
        }
      ]
    }) as any;
    const detailSlots = ref({
      detail: () => {
        return (
          <div class="item_right">
            <ElDatePicker
              v-model={date.chart}
              type="year"
              class="month_selector"
              range-separator="/"
              clearable={false}
              // @ts-ignore
              onChange={complaintChartList}
            />
          </div>
        );
      }
    });

    getComplaint().then((res) => {
      detail.value = res.data;
    });

    const viewDetail = () => {
      dialogVisible.value = true;
      date.list = JSON.parse(JSON.stringify(date.chart));
      getComplaintData();
    };

    const selectYear = (dateYear: Date) => {
      date.list = dateYear;
      getComplaintData();
    };

    const viewComplaintDetail = (month: number) => {
      date.detail = new Date(month * 1000);
      dialogDetailVisible.value = true;
      nextTick(() => {
        getComplaintDetail();
      });
    };
    const complaintChartList = () => {
      const year = date.chart.getFullYear();
      complaintList({ year }).then((res) => {
        const data = {
          target: [],
          reality: [],
          rate: [],
          month: []
        } as AnyObject;
        res.data.list.forEach((_item: AnyObject) => {
          data.target.push(_item.target);
          data.reality.push(_item.reality);
          data.rate.push(_item.rate);
          data.month.push(_item.month);
        });
        option.value.series[0].data = data.target;
        option.value.series[1].data = data.reality;
        option.value.series[2].data = data.rate;
        option.value.xAxis[0].data = data.month;
      });
    };
    function getComplaintData() {
      loadingCommon.value = true;
      const year = new Date(date.list).getFullYear();
      complaintList({ year }).then((res) => {
        tableData.value = res.data.list;
        loadingCommon.value = false;
      });
    }
    const getComplaintDetail = () => {
      const loadingInstance = ElLoading.service({ target: '.table_wrap' });

      const month = ('' + (date.detail.getMonth() + 1)).padStart(2, '0');
      const year = date.detail.getFullYear();
      detailData.value.number=0;
      complaintDetail({ month: year + '-' + month }).then((res) => {
        detailData.value = res.data;
        loadingInstance.close();
      });
    };
    const getDReportDetail = () => {
      loadingReport.value = true;
      const month = ('' + (date.report.getMonth() + 1)).padStart(2, '0');
      const year = date.report.getFullYear();
      dReportDetail({
        page: pageable.page,
        pageSize: pageable.pageSize,
        month: year + '-' + month
      }).then((res) => {
        reportData.value = res.data.list;
        pageable.total = res.data.total;
        loadingReport.value = false;
      });
    };
    const viewReport = () => {
      reportVisible.value = true;
      date.report = new Date();
      pageable.page = 1;
      pageable.pageSize = 15;
      getDReportDetail();
    };
    complaintChartList();

    return () => (
      <SheltV2
        title="客诉情况"
        more="查看详情"
        v-slots={detailSlots.value}
        onViewDetail={viewDetail}
        question="<div><p>【该数据每日02:00更新一次】</p><p>客诉情况是汇总海外业务工单和电商/海外线下工单的客诉工单，本月的实际客诉、目标客诉和相较上月同期降幅。</p></div>"
      >
        <Echarts option={option.value} />
        <div class="complaint flex-start">
          <div class="complaint_item">
            <div class="title">本月目标数量</div>
            <div class="num">{detail.value?.target_number}</div>
          </div>
          <div class="complaint_item">
            <div class="title">本月实际数量</div>
            <div class="num">{detail.value?.number}</div>
            <div class="fill">
              较上月同期降幅：<span>{detail.value?.decrease}%</span>
            </div>
          </div>
          <div class="complaint_item">
            <div class="flex-start">
              <div class="title">本月8D报告</div>
              <ElTooltip
                effect="light"
                placement="top"
                content="8D报告是指因批量客诉事件、生产异常事故而编制的系统性的解决方案报告。"
              >
                <ElImage
                  style={{ width: '15px' }}
                  src={`${VITE_STATIC_URL}/tcpl/question.png`}
                ></ElImage>
              </ElTooltip>
            </div>
            <div style={{ color: '#de0404' }} class="num">
              {detail.value?.report}
            </div>
            <div
              class="flex-start hover-color fill detail"
              onClick={viewReport}
            >
              查看详情
              <ElIcon>
                <ArrowRight />
              </ElIcon>
            </div>
          </div>
        </div>
        <ElDialog
          lock-scroll
          draggable
          v-model={dialogVisible.value}
          title="客诉情况"
          style={{ maxWidth: '800px', with: 'auto' }}
        >
          <ElDatePicker
            v-model={date.list}
            type="year"
            class="month_selector"
            range-separator="-"
            clearable={false}
            // @ts-ignore
            onChange={selectYear}
          />
          <ElTable
            v-loading={loadingCommon.value}
            header-row-class-name="table_header"
            size="small"
            data={tableData.value}
          >
            <ElTableColumn prop="month" label="日期" />
            <ElTableColumn prop="target" label="目标投诉" />
            <ElTableColumn prop="reality" label="实际投诉" />
            <ElTableColumn
              label="环比降幅"
              v-slots={{ default: ({ row }: AnyObject) => <p>{row.rate}%</p> }}
            />
            <ElTableColumn
              width="45px"
              label="详情"
              v-slots={{
                default: ({ row }: AnyObject) => (
                  <div
                    class="co-7 hover-color"
                    onClick={() => viewComplaintDetail(row.time)}
                  >
                    详情
                  </div>
                )
              }}
            />
          </ElTable>
        </ElDialog>
        <ElDialog
          lock-scroll
          draggable
          v-model={dialogDetailVisible.value}
          title="客诉情况"
          style={{ maxWidth: '800px', with: 'auto' }}
        >
          <div class="flex-between">
            <ElDatePicker
              v-model={date.detail}
              type="month"
              class="month_selector"
              range-separator="-"
              clearable={false}
              // @ts-ignore
              onChange={getComplaintDetail}
            />
            <p style={{ color: '#000', fontSize: '14px' }}>
              客诉工单总数：{detailData.value.number}
            </p>
          </div>
          <div class="table_wrap flex-between">
            <div class="table_item">
              <ElTable
                header-row-class-name="table_header"
                size="small"
                v-loading={loadingDetail.value}
                data={detailData.value.issueTypeInfoData}
              >
                <ElTableColumn prop="name" label="问题类型（大类）" />
                <ElTableColumn width="70" prop="number" label="客服单数" />
              </ElTable>
            </div>
            <div class="table_item">
              <ElTable
                header-row-class-name="table_header"
                size="small"
                data={detailData.value.deviceTypeInfoData}
              >
                <ElTableColumn prop="name" label="产品名称" />
                <ElTableColumn width="70" prop="number" label="客服单数" />
              </ElTable>
            </div>
          </div>
        </ElDialog>
        <ElDialog
          lock-scroll
          draggable
          v-model={reportVisible.value}
          title="8D报告"
          style={{ maxWidth: '800px', with: 'auto' }}
        >
          <ElDatePicker
            v-model={date.report}
            type="month"
            class="month_selector"
            range-separator="-"
            clearable={false}
            // @ts-ignore
            onChange={getDReportDetail}
          />
          <ElTable
            v-loading={loadingReport.value}
            header-row-class-name="table_header"
            size="small"
            data={reportData.value}
          >
            <ElTableColumn prop="date" label="投诉日期" />
            <ElTableColumn prop="title" label="标题" />
            <ElTableColumn prop="name" label="小组成员" />
            <ElTableColumn
              width="45px"
              label="详情"
              v-slots={{
                default: ({ row }: AnyObject) => (
                  <a class="co-7" href={row.url} target="_blank">
                    详情
                  </a>
                )
              }}
            />
          </ElTable>
        </ElDialog>
      </SheltV2>
    );
  }
});
